package controller;

import model.User;

import java.sql.*;

/**
 * 用户DAO类
 */
public class UserDao {
    /**
     * 登录验证
     * @param connection
     * @param user
     * @return
     * @throws SQLException
     */
    public User login(Connection connection, User user) throws SQLException {
        /*
        * 1. PreparedStatement ps = null;
        * 2. String sql = "select *from users where username = ?";
        * 3. ps = connection.prepareStatement(sql);
        * 4. ps.setString(1,user.getUsername());
        * 5. ResultSet res = ps.executeQuery();
        * */
        User resUser = null;
        PreparedStatement ps = null;
        String sql = "select *from users where username=? and password=?;";
        ps = connection.prepareStatement(sql);
//        sql = sql.replace("**", user.getUsername());
//        sql = sql.replace("&&", user.getPassword());
        ps.setString(1,user.getUsername());
        ps.setString(2,user.getPassword());
        System.out.println(sql);
//        Statement statement = connection.createStatement();
        ResultSet res = ps.executeQuery();
        //查到结果就将结果存到resUser中返回
        if(res.next()){
             resUser = new User(res.getString("username"),res.getString("password"));
             resUser.setId(res.getInt("id"));
        }
        return resUser;
    }
}
